<template>
  <base-table-layout
    title="司机信息管理"
    :total="total"
    :current-page="currentPage"
    :page-size="pageSize"
    @update:currentPage="val => currentPage = val"
    @update:pageSize="val => pageSize = val"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  >
    <!-- 搜索区域 -->
    <template #search>
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item>
          <el-input
            v-model="searchForm.keyword"
            placeholder="司机姓名/手机号/车牌号"
            style="width: 200px;"
            class="filter-item"
            @keyup.enter.native="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="handleSearch"
          >搜索</el-button>
          <el-button
            type="info"
            icon="el-icon-refresh"
            @click="resetSearch"
          >重置</el-button>
        </el-form-item>
      </el-form>
    </template>

    <!-- 操作区域 -->
    <template #operation>
      <el-button
        type="success"
        icon="el-icon-plus"
        @click="handleAdd"
      >新增司机</el-button>
    </template>

    <!-- 表格区域 -->
    <template #table>
      <div class="table-wrapper">
        <el-table
          v-loading="loading"
          :data="driverList"
          border
          style="width: 100%"
        >
          <el-table-column prop="driverId" label="司机ID" width="80" align="center" />
          <el-table-column prop="driverName" label="司机姓名" min-width="120" align="center" />
          <el-table-column prop="phone" label="联系电话" min-width="120" align="center" />
          <el-table-column prop="licensePlate" label="车牌号" min-width="120" align="center" />
          <el-table-column prop="statusDesc" label="状态" min-width="100" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === 0 ? 'success' : 'warning'">
                {{ scope.row.statusDesc }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="180" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button 
                size="mini" 
                :type="scope.row.status === 0 ? 'warning' : 'success'"
                @click="handleUpdateStatus(scope.row)"
              >
                {{ scope.row.status === 0 ? '设为配送中' : '设为空闲' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </template>

    <!-- 弹窗区域 -->
    <template #dialogs>
      <!-- 新增/编辑对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" :close-on-click-modal="false">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="dialog-form">
          <el-form-item label="司机姓名" prop="driverName">
            <el-input v-model="form.driverName" placeholder="请输入司机姓名" />
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入联系电话" />
          </el-form-item>
          <el-form-item label="车牌号" prop="licensePlate">
            <el-input v-model="form.licensePlate" placeholder="请输入车牌号" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </div>
      </el-dialog>
    </template>
  </base-table-layout>
</template>

<script>
import request from '@/utils/request'
import _ from 'lodash'
import BaseTableLayout from '@/components/BaseTableLayout.vue'

export default {
  name: 'DriverView',
  components: {
    BaseTableLayout
  },
  data() {
    return {
      loading: false,
      searchForm: {
        keyword: ''
      },
      driverList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      isEdit: false,
      form: {
        driverName: '',
        phone: '',
        licensePlate: ''
      },
      rules: {
        driverName: [
          { required: true, message: '请输入司机姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        licensePlate: [
          { required: true, message: '请输入车牌号', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    dialogTitle() {
      return this.isEdit ? '编辑司机信息' : '新增司机'
    }
  },
  created() {
    this.fetchDriverList()
  },
  methods: {
    // 获取司机列表
    async fetchDriverList() {
      try {
        this.loading = true
        const response = await request.get('/driver/page', {
          params: {
            pageNum: this.currentPage,
            pageSize: this.pageSize,
            keyword: this.searchForm.keyword || undefined
          }
        })
        
        if (response.records) {
          this.driverList = response.records
          this.total = response.total
        }
      } catch (error) {
        console.error('获取司机列表失败:', error)
        this.$message.error('获取司机列表失败')
      } finally {
        this.loading = false
      }
    },

    handleSearch: _.debounce(function() {
      this.currentPage = 1
      this.fetchDriverList()
    }, 300),

    resetSearch() {
      this.searchForm.keyword = ''
      this.handleSearch()
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.fetchDriverList()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchDriverList()
    },

    handleAdd() {
      this.isEdit = false
      this.form = {
        driverName: '',
        phone: '',
        licensePlate: ''
      }
      this.dialogVisible = true
    },

    handleEdit(row) {
      this.isEdit = true
      this.form = {
        driverId: row.driverId,
        driverName: row.driverName,
        phone: row.phone,
        licensePlate: row.licensePlate
      }
      this.dialogVisible = true
    },

    async handleUpdateStatus(row) {
      try {
        const newStatus = row.status === 0 ? 1 : 0
        const statusText = newStatus === 0 ? '空闲' : '配送中'
        
        await this.$confirm(`确认将司机状态修改为${statusText}吗？`, '提示', {
          type: 'warning'
        })
        
        await request.put(`/driver/${row.driverId}/status/${newStatus}`)
        this.$message.success('状态更新成功')
        this.fetchDriverList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('更新状态失败:', error)
          this.$message.error('更新状态失败')
        }
      }
    },

    async handleSubmit() {
      try {
        await this.$refs.form.validate()
        
        if (this.isEdit) {
          await request.put('/driver', this.form)
          this.$message.success('编辑成功')
        } else {
          await request.post('/driver', this.form)
          this.$message.success('添加成功')
        }
        
        this.dialogVisible = false
        this.fetchDriverList()
      } catch (error) {
        if (error !== false) {
          console.error(this.isEdit ? '编辑司机失败:' : '添加司机失败:', error)
          this.$message.error(this.isEdit ? '编辑司机失败' : '添加司机失败')
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.search-form {
  display: flex;
  align-items: center;
  margin-bottom: 0;
  
  .el-form-item {
    margin-bottom: 0;
    margin-right: 10px;
  }
}

.table-wrapper {
  margin: 8px 0;
  
  .el-table {
    margin-bottom: 0;
  }
}

.dialog-form {
  padding: 20px 40px;
  
  .el-form-item:last-child {
    margin-bottom: 0;
  }
}

.dialog-footer {
  text-align: right;
  padding: 10px 20px;
  border-top: 1px solid #dcdfe6;
}

:deep(.el-dialog__body) {
  padding: 0;
}

:deep(.el-dialog__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #dcdfe6;
}
</style> 